from django import forms
from web.forms.bootstrap import BootStrapForm
from web import models
from django.core.exceptions import ValidationError
from web.forms.widgets import ColorRadioselect

class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ["color"]

    # 项目中的项目描述默认是以Charfield表示，在此重写加入插件为textarea改变
    # 方式一：
    # desc = forms.CharField(widget=forms.Textarea(attrs={'xx':123}))
    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        # 方式二:集体重写插件
        widgets = {
            # 'desc': forms.Textarea(attrs={'xx':123})
            'desc': forms.Textarea,
            'color': ColorRadioselect(attrs={'class':'color-radio'}),  # 从下拉菜单变成按钮
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        """项目校验"""
        name = self.cleaned_data['name']
        # 1.当前用户是否已经创建过此项目?
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('项目名已存在')
        # 2.当前用户是否还有额度
        # 最多创建的项目
        # self.request.tracer.price_policy.project_num
        # 现在已经创建的项目
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超过限制，请购买套餐')
        return name
